package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.pojo.MarketAdmin;

import com.cskaoyan.bean.pojo.MarketRole;
import com.cskaoyan.bean.pojo.MarketStorage;
import com.cskaoyan.bean.vo.AdminAdminListVo;
import com.cskaoyan.bean.vo.AdminCreatePicStoreVo;
import com.cskaoyan.bean.vo.AdminLogListVo;
import com.cskaoyan.bean.vo.AdminUpdateVo;

import com.cskaoyan.bean.vo.*;

import com.cskaoyan.service.SystemService;
import com.cskaoyan.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.sound.sampled.Line;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Objects;
import java.util.UUID;

/**
 * @author :beauty
 * @version : $version
 * @date :Created in 2022/4/6   16:03
 * @description:
 * @return:
 */
@RestController
@RequestMapping("admin")
public class  SystemController {

    @Autowired
    SystemService systemService;

    //管理员管理模块
    //查询展示某页管理员信息
    @RequestMapping("admin/list")
    public BaseRespVo adminList(AdminListBo adminListBo) {
        AdminAdminListVo adminAdminListVo = systemService.query(adminListBo);
        return BaseRespVo.ok(adminAdminListVo);
    }

    //新增管理员
    @RequestMapping("admin/create")
    public BaseRespVo adminCreate(@RequestBody @Validated AdminCreateBo adminCreateBo, BindingResult bindingResult) {
        //增加用户名，密码的长度校验异常处理
        if (bindingResult.hasFieldErrors()) {
            return BaseRespVo.fail(101, "用户名密码只能在30位之内");
        }
        MarketAdmin marketAdmin = systemService.insert(adminCreateBo);
        return BaseRespVo.ok(marketAdmin);
    }

    /*//新增管理员上传头像
    @RequestMapping("storage/create")
        public BaseRespVo adminCreatePicStore(@RequestBody  MultipartFile adminPic, HttpRequest request) throws IOException {
            String filename = adminPic.getOriginalFilename();
            String contentType = adminPic.getContentType();
            long size = adminPic.getSize();

        System.out.println(filename);
        System.out.println(contentType);
        System.out.println(size);
        File file = new File("D:\\marketPicture",filename);
        adminPic.transferTo(file);
        String url = request.getURI().toURL().toString();
        AdminCreatePicStoreVo addPic = systemService.addPic(filename,contentType,size,url);

        return BaseRespVo.ok(addPic);
    }*/




    //修改管理员信息
    @RequestMapping("admin/update")
    public BaseRespVo adminUpdate(@RequestBody AdminCreateBo adminCreateBo) {
        if (adminCreateBo.getId() == 1) {
            return BaseRespVo.fail(10000, "超级管理员不可修改");
        }
        AdminUpdateVo adminUpdateVo = systemService.adminUpdate(adminCreateBo);
        return BaseRespVo.ok(adminUpdateVo);
    }

    //删除管理员
    @RequestMapping("admin/delete")
    public BaseRespVo adminDelete(@RequestBody AdminCreateBo adminCreateBo) {
        if (adminCreateBo.getId() == 1) {
            return BaseRespVo.fail(1000, "超级管理员不可删除");
        }
        systemService.delete(adminCreateBo);
        return BaseRespVo.ok();
    }

    /*
    角色管理模块
     */
    //http://localhost:8083/admin/role/options
    @RequestMapping("role/options")
    public BaseRespVo roleOptions() {
        RoleOptionVo roleOption = systemService.queryAllRole();
        return BaseRespVo.ok(roleOption);
    }

    @GetMapping("role/list")
    public BaseRespVo roleList(RoleListBo roleListBo) {
        RoleListVo roleListVo= systemService.queryAllRoleList(roleListBo);
        return BaseRespVo.ok(roleListVo);
    }

    @PostMapping("role/create")
    public BaseRespVo roleCreate(@RequestBody @Validated RoleCreateBo roleCreateBo, BindingResult result) {
        if (result.hasFieldErrors()) {
            return BaseRespVo.fail(102, "角色名字只能在30位之内");
        }
        MarketRole marketRole = systemService.roleCreate(roleCreateBo);
        return BaseRespVo.ok(marketRole);
    }

    @PostMapping("role/update")
    public BaseRespVo roleUpdate(@RequestBody MarketRole marketRole) {
        if (marketRole.getId() == 1) {
            return BaseRespVo.fail(1000, "超级管理员不可修改");
        }
        systemService.updateRole(marketRole);
        return BaseRespVo.ok();
    }

    /**
     * 文琪修改：由于market_role表的name设置了UNIQUE，无法逻辑删除，只能真删
     * 创建日期：2022/04/08 21:16
     * @param  marketRole
     * @return com.cskaoyan.bean.BaseRespVo
     * @author ChengWenqi
     */
    /**
     * 罗旭欣修改：无法删除id为1的超级管理员
     * @param marketRole
     * @return
     */
    @PostMapping("role/delete")
    public BaseRespVo roleDelete(@RequestBody MarketRole marketRole) {
        if (marketRole.getId() == 1&&marketRole.getName().equals("超级管理员")) {
            return BaseRespVo.fail(10000, "超级管理员不可删除");
        }
        int code = systemService.deleteRole(marketRole);
        if (code == 200) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.fail(10000, "角色不存在，无法删除！");
    }


    /**
     * 获取id对应角色的授权信息
     * 创建日期：2022/04/08 19:26
     * @param  roleId 角色id
     * @return com.cskaoyan.bean.BaseRespVo
     * @author ChengWenqi
     */
    @GetMapping("role/permissions")
    public BaseRespVo rolePermissionsGet(Integer roleId) {
        if (roleId != null) {
            RolePermissionsVO rolePermissionVO = systemService.queryPermissions(roleId);
            return BaseRespVo.ok(rolePermissionVO);
        }
        return BaseRespVo.fail(10000, "角色不存在！");
    }

    /**
     * 更新角色id对应的授权信息
     * 创建日期：2022/04/08 20:51
     * @param  rolePermissionBO 包含角色id和更新后的授权信息
     * @return com.cskaoyan.bean.BaseRespVo
     * @author ChengWenqi
     */
    @PostMapping("role/permissions")
    public BaseRespVo rolePermissionsUpdate(@RequestBody @Validated RolePermissionBO rolePermissionBO) {
        int code = systemService.updateRolePermissions(rolePermissionBO);
        if (code == 200) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.fail(10000,"角色id不存在！");
    }


    //操作日志
    @RequestMapping("log/list")
    public BaseRespVo adminLogList(AdminLogListBo logListBo) {
        AdminLogListVo adminLogListVo = systemService.queryLog(logListBo);
        return BaseRespVo.ok(adminLogListVo);
    }

    /*
    对象储存模块
     */
    @RequestMapping("storage/list")
    public BaseRespVo StorageList(BaseParam baseParam,String key,String name) {
        StorageListVo storageListVo = systemService.storageList(baseParam, key, name);
        return BaseRespVo.ok(storageListVo);
    }

    //新增对象
    @RequestMapping("storage/create")
    public BaseRespVo adminStorageCreate(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();

        // 解决文件名重复问题：用UUID工具类
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        // 获取原始文件的后缀
        String[] split = originalFilename.split("\\.");
        String finalFileName = uuid + "." + split[1];
        String relativePath = Constant.pictureLocation + finalFileName;
        // 将文件保存到本地
        File fileLocal = new File(Constant.staticResources + relativePath);
        if (!fileLocal.getParentFile().exists()) {
            fileLocal.getParentFile().mkdirs();
        }

        try {
            file.transferTo(fileLocal);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将图片存入数据库，同时返回数据库记录
        MarketStorage marketStorage = systemService.storageCreate(file, finalFileName, relativePath);

        return BaseRespVo.ok(marketStorage);
    }

    //修改对象
    @RequestMapping("storage/update")
    public BaseRespVo updateStorage(@RequestBody MarketStorage marketStorage) {
        MarketStorage marketStorage1 = systemService.updateStorage(marketStorage);
        return BaseRespVo.ok(marketStorage1);
    }

    //删除储存的对象（假删，为了方便误删后找回）
    @RequestMapping("storage/delete")
    public BaseRespVo deleteStorage(@RequestBody MarketStorage marketStorage) {
        systemService.deleteStorage(marketStorage);
        return BaseRespVo.ok();
    }

}
